package com.dd.stack.mybatisplus.service.inner.impl.mvcc;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.stack.mybatisplus.config.exception.DomainException;
import com.dd.stack.mybatisplus.mapper.mvcc.ThumbUserMapper;
import com.dd.stack.mybatisplus.pojo.DO.mvcc.thumb.ThumbUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/12 14:39
 * @Description 类功能作用说明
 */
@Service
@DS("thumb")
@RequiredArgsConstructor
public class ThumbUserServiceImpl extends ServiceImpl<ThumbUserMapper, ThumbUser> {

    private final ThumbUserMapper thumbUserMapper;

    @Transactional(rollbackFor = Exception.class)
    public void descUserJavaFieldNoLock() {
        // 方法1：直接执行查询看日志
        QueryWrapper<ThumbUser> qw = new QueryWrapper<>();
        qw.eq("id", 94);
        ThumbUser user = thumbUserMapper.selectOne(qw);
        Long num = user.getNum();
        user.setNum(--num);
        thumbUserMapper.updateById(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public void descUserJavaFieldForUpdate(Long id) {
        // 使用行排他锁防止并发问题
        ThumbUser user = thumbUserMapper.selectForUpdate(id);
        if (user == null) {
            throw new DomainException(404, "用户不存在");
        }
        if (user.getNum() <= 0) {
            throw new DomainException(400, "num数字已经为0，不可再执行减操作");
        }

        try {
            user.setNum(user.getNum() - 1);
            thumbUserMapper.updateById(user);
        } catch (Exception e) {
            throw new DomainException(500, "系统异常，请重试");
        }
    }
}
